// ExampleComponent.tsx
import { dataKeys } from '../dataKeys';
import { useBatch, useListen, useSelect } from '../hooks';

export const ExampleComponent: React.FC = () => {
  const [testValue, setTestValue] = useListen(dataKeys.TEST);
  const [count, setCount] = useListen(dataKeys.COUNT);
  const [user, setUser] = useListen(dataKeys.USER);
  const batchUpdate = useBatch();

  // 使用选择器获取派生状态
  const userName = useSelect(dataKeys.USER, (user) => user.name);
  const isAdult = useSelect(dataKeys.USER, (user) => user.age >= 18);

  const handleSingleUpdate = () => {
    setTestValue(`Updated at ${new Date().toLocaleTimeString()}`);
    setCount((prev) => prev + 1);
  };

  const handleBatchUpdate = () => {
    batchUpdate([
      [dataKeys.TEST, `Batch updated at ${new Date().toLocaleTimeString()}`],
      [dataKeys.COUNT, count + 5],
      [dataKeys.USER, { ...user, name: 'Batch User', age: user.age + 1 }],
    ]);
  };

  const updateUser = () => {
    setUser({
      name: 'John Doe',
      age: 30,
    });
  };

  return (
    <div>
      <h1>Enhanced Context Example</h1>

      <div>
        <p>Test Value: {testValue}</p>
        <p>Count: {count}</p>
        <p>
          User: {user.name} ({user.age} years old)
        </p>
        <p>User Name: {userName}</p>
        <p>Is Adult: {isAdult ? 'Yes' : 'No'}</p>
      </div>

      <button type="button" onClick={handleSingleUpdate}>
        Single Update
      </button>
      <button type="button" onClick={handleBatchUpdate}>
        Batch Update
      </button>
      <button type="button" onClick={updateUser}>
        Update User
      </button>

      {/* 类型安全验证 */}
      <div
        style={{ marginTop: '20px', padding: '10px', border: '1px solid #ccc' }}
      >
        <h3>TypeSafe Operations:</h3>
        <button type="button" onClick={() => setTestValue('New String Value')}>
          Set String (Correct)
        </button>
        <button type="button" onClick={() => setCount(100)}>
          Set Number (Correct)
        </button>
        {/* 这些会在编译时报错 */}
        {/* 
        <button type="button" onClick={() => setTestValue(123)}>Error: Number to String</button>
        <button type="button" onClick={() => setCount("hello")}>Error: String to Number</button>
        */}
      </div>
    </div>
  );
};
